#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

template <typename Container>
void display(const Container &con){
    for(auto &elem : con){
        cout<<elem<<" ";
    }
    cout<<endl;
}

void printcapacity(const vector<int> &con){
    cout<<"size()="<<con.size()<<endl;
    cout<<"capacity()="<<con.capacity()<<endl;
}

void test(){
    
    vector<int> number={1,2,4,6,8,9,3,6,7};
    display(number);
    printcapacity(number);
    //number.reserve(100);  预留空间，capacity为100
    //printcapacity(number);

    cout<<endl<<"在vector尾部插入与删除"<<endl;
    number.push_back(11);
    number.push_back(22);
    display(number);
    printcapacity(number);
    number.pop_back();
    display(number);
    printcapacity(number);

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    cout<<endl<<"在任意位置进行插入"<<endl;
    auto it = number.begin();
    ++it;
    ++it;
    cout<<*it<<endl;
    number.insert(it,33);  //找一个位置插入一个元素
    display(number);
    cout<<"此时迭代器指向位置的元素变了，"<<*it<<endl;
    printcapacity(number);

    cout<<endl;
    number.insert(it,3,666);    //找一个位置，插入count个value
    display(number);
    cout<<"此时迭代器指向位置的元素变了，"<<*it<<endl;
    printcapacity(number);

    cout<<endl;
    vector<int> vec={200,500,600,300};
    //迭代器范围地插入
    number.insert(it,vec.begin(),vec.end());
    display(number);
    cout<<"此时迭代器指向位置的元素变了，"<<*it<<endl;
    printcapacity(number);
    
    cout<<endl;
    number.insert(it,{123,456,789});    //大括号插入
    display(number);
    cout<<"此时vector发生扩容，it仍在原来位置，*it变为乱值"<<*it<<endl;
    printcapacity(number);
    //迭代器失效，如果再用就会报错
    //解决方法如下，每次使用前将迭代器重新置位一下
    //it = number.begin();
    //++it;
    //++it;
    
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    cout<<endl<<"获取第一个、最后一个元素"<<endl;
    cout<<number.front()<<endl;
    cout<<number.back()<<endl;

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    cout<<endl<<"清空所有元素"<<endl;
    number.clear();
    number.shrink_to_fit();
    printcapacity(number);
}

int main()
{   
    test();
    return 0;
}

